angular.module('mvcApp.my-favorites', [
    'ngRoute',
    'ngResource'
]).config(['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/my_favorites', {
            templateUrl: 'static/views/my-favorites.html',
            controller: 'MyFavoritesCtrl'
        });
}]).controller('MyFavoritesCtrl', ['$scope', '$http', '$location', 'User', '$routeParams', 'Shop', 'Category', 'Product',
    function ($scope, $http, $location, User, $routeParams, Shop, Category, Product) {
        $scope.products = [];
        $scope.shops = [];
        $scope.productsPage = 1;
        $scope.shopsPage = 1;
        $scope.productsTotal = 0;
        $scope.shopsTotal = 0;
        $scope.pageSize = 10;
        $scope.loadProducts = function() {
            if($scope.productsPage < 1) {
                $scope.productsPage = 1;
            }
            Product.getUserCollectedProducts(WebApp.currentUser.id, $scope.productsPage, $scope.pageSize)
                .then(function(records, total) {
                    $scope.products = records;
                    $scope.productsTotal = total;
                    $scope.$apply();
                }).catch(function(err) {
                    if(err) {
                        alert(err);
                    }
                });
        };
        $scope.loadShops = function() {
            if($scope.shopsPage < 1) {
                $scope.shopsPage = 1;
            }
            Shop.getUserCollectedShops(WebApp.currentUser.id, $scope.shopsPage, $scope.pageSize)
                .then(function(records, total) {
                    $scope.shops = records;
                    $scope.shopsTotal = total;
                    $scope.$apply();
                }).catch(function(err) {
                    if(err) {
                        alert(err);
                    }
                });
        };
        if(WebApp.currentUser.id) {
            $scope.loadProducts();
            $scope.loadShops();
        } else {
            User.currentUserInfo()
                .then(function(userInfo) {
                    _.extend(WebApp.currentUser, userInfo);
                    $scope.loadProducts();
                    $scope.loadShops();
                }).catch(function(err) {
                    if(err) {
                        alert(err);
                    }
                });
        }
    }]);